((doc,storage)=>{
const oList=doc.querySelector('#list')
const oMsg=doc.querySelector('#message')
const oSendBtn=doc.querySelector('#send')
const ws=new WebSocket('ws:localhost:8000')
let username=''
const init=()=>{
bindEvent()
}

function bindEvent(){
    oSendBtn.addEventListener('click',handleSendBtnClick,false)
        ws.addEventListener('open',handleOpen,false)
        ws.addEventListener('close',handleClose,false)
        ws.addEventListener('error',handleError,false)
        ws.addEventListener('message',handleMessage,false)
}
  //发送请求
function handleSendBtnClick(){
      const msg=oMsg.value;
      if(!msg.trim().length){
        return
      }

      ws.send(
        JSON.stringify(   {
        user:username,
        dateTime:new Date().getTime(),
        message:msg
      })
     )

     oMsg.value=''
}

function handleOpen(){
    console.log("open");
    username=storage.getItem('username')
    if(!username){
        location.href=entry.html
    }
}
function handleClose(){
    
}
function handleError(){
    
}
function handleMessage(e){

    const msgdata=e.data
    oList.appendChild(createMsg(msgdata))
  
}
function createMsg(data){
    let objdata=JSON.parse(data)
    const {user,dateTime,message}=objdata
    console.log(message);
    const oItem=doc.createElement('li')
    oItem.innerHTML=`
    <p>
    <span>${user}</span>
    <i>${new Date(dateTime)}</i>
    </p>
    <p>消息:${message}</p>
    `

    return oItem
}
init()
})(document,localStorage)